package log

import (
	"backend/config"
	"log"

	"strings"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var Logger *zap.Logger

func LogInit(cfg config.Logging) {
	var Level zapcore.Level
	switch strings.ToLower(cfg.Level) {

	case "debug":
		Level = zapcore.DebugLevel
	case "info":
		Level = zapcore.InfoLevel
	case "warn":
		Level = zapcore.WarnLevel
	case "error":
		Level = zapcore.ErrorLevel
	default:
		Level = zapcore.InfoLevel
	}
	config := zap.Config{
		Encoding:         "console",                   // 使用 console 格式
		Level:            zap.NewAtomicLevelAt(Level), // 设置日志等级
		OutputPaths:      []string{cfg.Stdout},        // 日志文件路径或 "stdout"
		ErrorOutputPaths: []string{cfg.Stderr},        // 错误日志文件路径或 "stderr"
		EncoderConfig: zapcore.EncoderConfig{
			TimeKey:       "time",
			LevelKey:      "level",
			NameKey:       "logger",
			CallerKey:     "caller",
			MessageKey:    "msg",
			StacktraceKey: "stacktrace",
			LineEnding:    zapcore.DefaultLineEnding,
			EncodeLevel:   zapcore.CapitalLevelEncoder,
			EncodeTime:    zapcore.ISO8601TimeEncoder,
			EncodeCaller:  zapcore.FullCallerEncoder,
		},
	}
	var err error
	Logger, err = config.Build()
	if err != nil {
		log.Fatalln(err)
	}
	defer Logger.Sync()
}
